import log4js from 'log4js'
import { Color } from './common.js'
import _ from 'lodash'

if (!global.logger) {
  log4js.configure({
    appenders: {
      console: {
        type: 'console',
        layout: {
          type: 'pattern',
          pattern: `${Color.green('[ad-APIS]')}%[[%d{hh:mm:ss.SSS}][%4.4p]%]%m`
        }
      }
    },
    categories: {
      default: { appenders: ['console'], level: 'info' }
    },
    pm2: true
  })
}

/**
 * 日志记录类
 * @class Logger
 * @param {string | number | null} port - 端口号
 */
export class Logger {
  constructor (port) {
    this.logger = global.logger || log4js.getLogger()
    this.port = port
  }

  trace (message, ...args) {
    this.logger.trace(message, ...args)
  }

  debug (message, ...args) {
    this.logger.debug(message, ...args)
  }

  info (message, ...args) {
    this.logger.info(message, ...args)
  }

  warn (message, ...args) {
    this.logger.warn(message, ...args)
  }

  error (message, ...args) {
    this.logger.error(message, ...args)
  }

  fatal (message, ...args) {
    this.logger.fatal(message, ...args)
  }

  mark (message, ...args) {
    this.logger.mark(message, ...args)
  }

  server (type, ...args) {
    this.logWithPort(type, `${this.port ? `[${this.port}]` : ''}[Server]`, ...args)
  }

  plugin (type, ...args) {
    this.logWithPort(type, `${this.port ? `[${this.port}]` : ''}[Plugin]`, ...args)
  }

  getRandomKeys () {
    return _.sample(Object.keys(Color).filter((key) => typeof Color[key] === 'function'))
  }

  /**
   * 根据端口记录日志
   * @param message message
   */
  logWithPort (type = 'info', ...args) {
    if (this[type]) {
      this[type](...args)
      return true
    } else {
      return false
    }
  }
}
